package com.eightbears.beboy.ui.merchant.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eightbears.beboy.R;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.qrcode.utils.CodeUtils;
import com.eightbears.beboy.entity.UserEntity;
import com.socks.library.KLog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 我的收款码
 */
public class QCCodePayActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.iv_qc_pay_qc)
    ImageView iv_qc_pay_qc;
    @BindView(R.id.rl_title_root)
    RelativeLayout rl_title_root;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    private Bitmap mImageQC;
    private View mViewPic;
    private UserEntity.Shop mShopsBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_gathering_code);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rl_title_root.setBackgroundColor(Color.parseColor("#4d7aad"));
        tv_title.setText("我的收款码");
        mShopsBean = SPUtil.getUser().getData().getShops().get(0);
        String shop_id = mShopsBean.getShop_id();
        String url = "beboy://shopPay/" + shop_id;
        mImageQC = CodeUtils.createImage(url, 150, 150, null);
        iv_qc_pay_qc.setImageBitmap(mImageQC);
        initPic();
    }

    private void initPic() {
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;     // 屏幕宽度（像素）
        int height = metric.heightPixels;   // 屏幕高度（像素）
        mViewPic = LayoutInflater.from(this).inflate(R.layout.view_qc_code_pay_keep, null, false);
        layoutView(mViewPic, width, height);
        ImageView iv_view_qc_pay_qc = (ImageView) mViewPic.findViewById(R.id.iv_view_qc_pay_qc);
        TextView tv_view_qc_title = (TextView) mViewPic.findViewById(R.id.tv_view_qc_title);
        tv_view_qc_title.setText(mShopsBean.getTitle());
        iv_view_qc_pay_qc.setImageBitmap(mImageQC);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @OnClick(R.id.tv_qc_pay_keep)
    void keep() {
        Bitmap bitmapFromView = loadBitmapFromView(mViewPic);
        File file = saveImage(bitmapFromView);
        ShowToast.showShortToast("保存图片到相册成功");
        KLog.e(file);
    }

    private Bitmap loadBitmapFromView(View v) {
        int w = v.getWidth();
        int h = v.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */

        v.layout(0, 0, w, h);
        v.draw(c);

        return bmp;

    }

    public File saveImage(Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(file);
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    //然后View和其内部的子View都具有了实际大小，也就是完成了布局，相当与添加到了界面上。接着就可以创建位图并在上面绘制了：
    private void layoutView(View v, int width, int height) {
        // 整个View的大小 参数是左上角 和右下角的坐标
        v.layout(0, 0, width, height);
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(10000, View.MeasureSpec.AT_MOST);
        /** 当然，measure完后，并不会实际改变View的尺寸，需要调用View.layout方法去进行布局。
         * 按示例调用layout函数后，View的大小将会变成你想要设置成的大小。
         */
        v.measure(measuredWidth, measuredHeight);
        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
    }
}
